package com.zm.demo.core.nio;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

import static java.lang.System.out;

/**
 * @author zoum
 * @create 2019/9/16 18:16
 */
public class SelectorT {

    public static void main(String[]args) throws Exception{

        Selector selector = Selector.open();

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.bind(new InetSocketAddress(9988));
        SelectionKey selectionKey = socketChannel.register(selector, SelectionKey.OP_CONNECT);
        while (true){
            int readyChannels = selectionKey.readyOps();
            if (readyChannels == 0) {
                out.println("readyChannels is 0");
                Thread.sleep(1000);
                continue;
            }
            Set<SelectionKey> selectKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey1 = iterator.next();
                if (selectionKey1.isConnectable()){
                    out.println("has connect");
                }
                iterator.remove();
            }
        }
    }
}
